package core.manager
{
	import core.object.SpriteSheet;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	public class SpriteSheetManager extends EventDispatcher
	{
		public function SpriteSheetManager()
		{
		}
		
		private static var _instance:SpriteSheetManager;
		
		public static function get instance():SpriteSheetManager {
			if(_instance == null){
				_instance = new SpriteSheetManager();
			}
			return _instance;
		}
		
		private var _items:Array;
		
		private var item:Object;
		
		public function load():void {
			if(this._items == null){
				return;
			}
			if(this._items.length == 0){
				this.dispatchEvent(new Event(Event.COMPLETE));
				return;
			}
			item = this._items.shift();
			var loader:Loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleted);
			loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onError);
			loader.load(new URLRequest(item.path));
		}
		
		private function onCompleted(event:Event):void {
			var loader:Loader = event.target.loader;
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onCompleted);
			loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onError);
			var bitmapData:BitmapData = Bitmap(event.target.content).bitmapData;
			var sheet:SpriteSheet = new SpriteSheet();
			for(var key:* in item){
				if(sheet.hasOwnProperty(key)){
					sheet[key] = item[key];
				}
			}
			sheet.parse(bitmapData);
			cache[sheet.id] = sheet;
			sheet.data = item;
			this.load();
		}
		
		private function onError(event:Event):void {
			
		}
		
		public function set items(value:Array):void {
			this._items = value;
			this.checkProps();
			this.load();
		}
		
		private function checkProps():void {
			for each(var object:Object in this._items){
				if(object.hasOwnProperty("isProperty")){
					this._props.push(object);
				}
			}
		}
		
		private var _props:Array = [];
		
		public function get props():Array {
			return this._props;
		}
		
		private var cache:Dictionary = new Dictionary(true);
		
		public function getSheet(value:*):SpriteSheet {
			return cache[value];
		}
	}
}